package cjlu.ea.h.controller;

import cjlu.ea.h.common.AuthUtil;
import cjlu.ea.h.common.R;
import cjlu.ea.h.common.TokenUtils;
import cjlu.ea.h.entity.SUser;
import cjlu.ea.h.entity.UserRoles;
import cjlu.ea.h.service.SUserService;
import cjlu.ea.h.service.UserRolesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true")
@Slf4j
public class UserLoginController {

    @Resource
    SUserService userService;
    @Resource
    AuthUtil authUtil;
    @Resource
    UserRolesService userRolesService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/login/{username}/{password}",method = RequestMethod.POST)
    public R Login(@PathVariable("username") String username,@PathVariable("password") String password){

        if(username==null){
            return R.error().message("用户名不为空");
        }
        //判断是否存在用户
        QueryWrapper<SUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",username);
        SUser user = userService.getOne(queryWrapper);
        if(user==null){
            return R.error().message("用户不存在");
        }else{
            if(!password.equals(user.getUserPassword())) {

                return R.error().message("密码错误");
            }
        }
        TokenUtils tokenUtils = new TokenUtils();

        String token = tokenUtils.createToken(username);

        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());


        log.info(formatter.format(date)+"登陆成功，生成token:"+token);

        UserRoles message = userRolesService.getById(user.getId());
        String roles = message.getRolesName();
        redisTemplate.opsForValue().set(token,roles,1 , TimeUnit.DAYS);
        log.info("user 的院校级权限放入完成... {}",roles);
        redisTemplate.opsForValue().set("UserRoles"+ user.getUserName(),user.getRoles());
        log.info("user 的管理员用户权限放入完成... key:{} value:{}","UserRoles"+user.getUserName(),user.getRoles());
        return R.ok().data("token",token);
    }

    @GetMapping("/info")
    public R UserInfo(HttpServletRequest request){

        String userRole =  authUtil.getAuthentications(request);
        return R.ok().data("roles","hello,"+userRole).data("name",userRole);
    }
}
